<?php
require_once('uml_common.php');

function loginUser($user, $pass) {
  if($pass != '' && md5($pass) == getPassword($user)) {
    $errorText = '';
    $_SESSION['validUser'] = true;
    $_SESSION['userName'] = $user;
  }
  else {
    $errorText = 'Invalid username or password!';
    $_SESSION['validUser'] = false;
  }
  return $errorText;
}

if(isset($_POST['submitBtn'])) {
  $username = isset($_POST['username']) ? $_POST['username'] : '';
  $password = isset($_POST['password']) ? $_POST['password'] : '';
  $error = loginUser($username, $password);
  if($error == '' && isset($_SESSION['destinationURI'])) {
    header('Location: ' . $_SESSION['destinationURI']);
  }
}
else {
  $error = '0';
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
<head>
 <title>User Management Lite</title>
 <link href="uml_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="uml_main">
    <?php if($error != '') {?>
      <div class="uml_caption">Login</div>
      <form class="uml_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
        <table>
          <tr><td>Username:</td><td> <input class="uml_input" name="username" type="text"  /></td></tr>
          <tr><td>Password:</td><td> <input class="uml_input" name="password" type="password" /></td></tr>
          <tr><td colspan="2" align="center"><input class="uml_submit" type="submit" name="submitBtn" value="Login" /></td></tr>
        </table>
      </form>
      &nbsp;<a href="uml_register.php">Register</a>
    <?php }
      if (isset($_POST['submitBtn'])){
    ?>
      <div class="uml_caption">Login result:</div>
      <div class="uml_result">
        <?php
          if($error == '') {
            echo "Welcome $username! <br/>You are logged in!<br/><br/>";
            echo '<a href="index.php">Now you can visit the index page!</a>';
          }
          else echo $error;
        ?>
      </div>
    <?php
      }
    ?>
  </div>
</body>
</html>